<template>
  <a-spin :spinning="loading">
    <a-form ref="formRef" v-bind="formItemLayout">
      <a-row>
        <a-col :span="12">
          <a-form-item label="企业名称" v-bind="validateInfos.name">
            <a-input v-model:value="formData.name" placeholder="请输入企业名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="企业电话" v-bind="validateInfos.phone">
            <a-input v-model:value="formData.phone" placeholder="请输入企业电话" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="企业税号" v-bind="validateInfos.tax">
            <a-input v-model:value="formData.tax" placeholder="请输入企业税号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="企业地址" v-bind="validateInfos.address">
            <a-input v-model:value="formData.address" placeholder="请输入企业地址" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="企业法人" v-bind="validateInfos.legal">
            <a-input v-model:value="formData.legal" placeholder="请输入企业法人" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="法人电话" v-bind="validateInfos.legalPhone">
            <a-input v-model:value="formData.legalPhone" placeholder="请输入法人电话" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开户行" v-bind="validateInfos.bankName">
            <a-input v-model:value="formData.bankName" placeholder="请输入开户行" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="银行账号" v-bind="validateInfos.bankAccount">
            <a-input v-model:value="formData.bankAccount" placeholder="请输入银行账号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="企业简介" v-bind="validateInfos.introduction">
            <a-textarea v-model:value="formData.introduction" rows="2" placeholder="请输入企业简介" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="收件地址" v-bind="validateInfos.receivedAddress">
            <a-input v-model:value="formData.receivedAddress" placeholder="请输入收件地址" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="收件人" v-bind="validateInfos.receivedName">
            <a-input v-model:value="formData.receivedName" placeholder="请输入收件人" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="收件电话" v-bind="validateInfos.receivedPhone">
            <a-input v-model:value="formData.receivedPhone" placeholder="请输入收件电话" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="设置税率" v-bind="validateInfos.taxRate">
            <a-input v-model:value="formData.taxRate" placeholder="请输入税率" style="width: 100%" :disabled="disabled" addon-after=" % "/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="合同文件" v-bind="validateInfos.contractFile">
            <j-upload :maxCount=5 bizPath="business/htwj" fileType="file" fileFormat="jpg,png,pdf,doc,docx" v-model:value="formData.contractFile" :disabled="disabled" ></j-upload>
            <span style="color: red;">支持jpg/png/pdf/doc/docx文件，最多5张，每张大小不超过5M</span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="法人身份证正面" v-bind="validateInfos.idCardZm">
	          <j-image-upload :fileMax=1 bizPath="business/sfz" v-model:value="formData.idCardZm" :disabled="disabled"></j-image-upload>
            <span style="color: red;">支持jpg/png文件，大小不超过2M</span>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="法人身份证反面" v-bind="validateInfos.idCardFm">
	          <j-image-upload :fileMax=1 bizPath="business/sfz" v-model:value="formData.idCardFm" :disabled="disabled"></j-image-upload>
            <span style="color: red;">支持jpg/png文件，大小不超过2M</span>
          </a-form-item>
        </a-col>
<!--        <a-col :span="12">
          <a-form-item label="营业执照" v-bind="validateInfos.businessLicense">
	          <j-image-upload :fileMax=1 bizPath="business/yyzz" v-model:value="formData.businessLicense" :disabled="disabled"></j-image-upload>
            <span style="color: red;">支持jpg/png文件，大小不超过2M</span>
          </a-form-item>
        </a-col>-->
      </a-row>
    </a-form>

    <div style="width: 100%;text-align: center;margin-top: 10px;">
      <a-button preIcon="ant-design:check-outlined" style="width: 126px" type="primary" @click="submitForm" :disabled="disabled">提 交</a-button>
    </div>
  </a-spin>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref, nextTick } from "vue";
import { saveOrUpdate } from "../CaishuiBusiness.api";
import { useMessage } from "/@/hooks/web/useMessage";
import { getValueType } from "/@/utils";
import JDictSelectTag from "/@/components/Form/src/jeecg/components/JDictSelectTag.vue";
import JSwitch from "/@/components/Form/src/jeecg/components/JSwitch.vue";
import JSelectMultiple from "/@/components/Form/src/jeecg/components/JSelectMultiple.vue";
import JUpload from "/@/components/Form/src/jeecg/components/JUpload/JUpload.vue";
import JImageUpload from "/@/components/Form/src/jeecg/components/JImageUpload.vue";
import { duplicateValidate } from "/@/utils/helper/validator";
import { Form } from "ant-design-vue";

const useForm = Form.useForm;

  export default defineComponent({
    name: "CaishuiBusinessForm",
    components:{
      JDictSelectTag,
      JSwitch,
      JSelectMultiple,
      JUpload,
      JImageUpload,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const { createMessage } = useMessage();
      const formRef = ref();
      const formData = reactive<Record<string, any>>({
        id: '',
        tenantId: '',
        userId: '',
        pid: '',
        type: 3,//商户类型：1-普通商户，2-API商户，3-渠道商户
        name: '',
        phone: '',
        tax: '',
        legal: '',
        legalPhone: '',
        address: '',
        introduction: '',
        bankName: '',
        bankAccount: '',
        receivedName: '',
        receivedPhone: '',
        receivedAddress: '',
        signingType: '',
        signingServiceType: '',
        receiptSms: '',
        batchImport: '',
        idCardZm: '',
        idCardFm: '',
        businessLicense: '',
        environment: '',
        contractFile: '',
        riskFile: '',
        taxRate: '',
      });

      //表单验证
      const validatorRules = reactive({
        name: [{ required: true, message: '请输入企业名称!'}, { validator: nameDuplicatevalidate }],
        phone: [{ required: true, message: '请输入企业电话!'},],
        // tax: [{ required: true, message: '请输入企业税号!'}, { validator: taxDuplicatevalidate }],
        // legal: [{ required: true, message: '请输入企业法人!'},],
        // address: [{ required: true, message: '请输入企业地址!'},],
        // bankName: [{ required: true, message: '请输入开户行!'},],
        // bankAccount: [{ required: true, message: '请输入银行账号!'}, { validator: bankAccountDuplicatevalidate }],
        // idCardZm: [{ required: true, message: '请上传身份证正面照!'},],
        // idCardFm: [{ required: true, message: '请上传身份证反面照!'},],
        // businessLicense: [{ required: true, message: '请上传营业执照!'},],
        // contractFile: [{ required: true, message: '请上传合同文件!'},],
        // riskFile: [{ required: true, message: '请上传风控表!'},],
        taxRate: [{ required: true, message: '请输入税率!'},{ validator: taxRateNumValidate }],
      });
      const {resetFields, validate, validateInfos, clearValidate} = useForm(formData, validatorRules, {immediate: true});
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
         let bool = false;
         if(props.formBpm === true){
           if(props.formData.disabled === false){
             bool = false;
           }else{
             bool =  true;
           }
         }
         bool = props.formDisabled;
        //清除表单验证
        clearValidate();
         return bool;
      });

      function add(record) {
        edit(record);
      }

      async function edit(record) {
        nextTick(() => {
          resetFields();
          //赋值
          Object.assign(formData, record);
          if(formData && formData.taxRate){
            formData.taxRate = (parseFloat(formData.taxRate)*100).toFixed(4);
          }
        });
      }

      /**
       * 提交数据
       */
      async function submitForm() {
        // 触发表单验证
        await validate();
        loading.value = true;
        const isUpdate = ref<boolean>(false);
        //数据格式化
        let model = formData;
        if (model.id) {//编辑
          isUpdate.value = true;
          model.updateBy = "";
          model.updateTime = "";
        }else {//新增
          model.createBy = "";
          model.createTime = "";
          model.sysOrgCode = "";
          model.updateBy = "";
          model.updateTime = "";
        }
        //循环数据
        for (let data in model) {
          //如果该数据是数组并且是字符串类型
          if (model[data] instanceof Array) {
            let valueType = getValueType(formRef.value.getProps, data);
            //如果是字符串类型的需要变成以逗号分割的字符串
            if (valueType === 'string') {
              model[data] = model[data].join(',');
            }
          }
        }
        console.log('表单提交数据', model)
        await saveOrUpdate(model, isUpdate.value)
          .then((res) => {
            if (res.success) {
              createMessage.success(res.message);
              //设置id
              formData.id = res.result;
              isUpdate.value = true;
              emit('success', formData);
            } else {
              createMessage.warning(res.message);
            }
          })
          .finally(() => {
            loading.value = false;
          });
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      async function nameDuplicatevalidate(_r, value) {
        return duplicateValidate('caishui_business', 'name', value, formData.id || '')
      }
      async function taxDuplicatevalidate(_r, value) {
        return duplicateValidate('caishui_business', 'tax', value, formData.id || '')
      }
      async function bankAccountDuplicatevalidate(_r, value) {
        return duplicateValidate('caishui_business', 'bank_account', value, formData.id || '')
      }
      function taxRateNumValidate(rule, value, callback){
        if(value){
          let reg = /^(([1-9][0-9]*)|([0]\.\d{0,4}|[1-9][0-9]*\.\d{0,5}))$/;
          if(!reg.test(value)){
            callback("税率必须为数字!");
          }else if(parseFloat(value) <= 0 || parseFloat(value) > 50){
            callback("税率必须大于0且小于等于50!");
          }else {
            callback();
          }
        }else {
          callback();
        }
      }

      return {
        validatorRules,
        validateInfos,
        loading,
        formData,
        setFieldsValue,
        formItemLayout,
        disabled,
        submitForm,
        add,
        edit,
      }
    }
  });
</script>
